package com.easyExcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.easyExcel.dto.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Part;
import java.io.InputStream;

/**
 * @Author：万意佳
 * @Date:
 * @Description:
 **/
@RequestMapping("/uploadExcel")
@ResponseBody
public class UploadExcel {

    @RequestMapping("/uploadExcel")
    @ResponseBody
    public String uploadExcel(@RequestParam("file") Part part) throws Exception {
        // 获取上传的文件流
        InputStream inputStream = part.getInputStream();
        // 读取Excel
        EasyExcel.read(inputStream, User.class,
                new AnalysisEventListener<User>() {
                    // 每解析一行数据,该方法会被调用一次
                    @Override
                    public void invoke(User data, AnalysisContext analysisContext) {
                        System.out.println("解析数据为:" + data.toString());
                    }

                    // 全部解析完成被调用
                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        System.out.println("解析完成...");
                        // 可以将解析的数据保存到数据库
                    }
                }).sheet().doRead();
        return "上传Excel文件成功";
    }
}